package entry;

import server.RoomManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

public class MemberSocket extends Thread{
    private Member member;
    private Socket socket;

    public MemberSocket(Socket socket){
        this.socket = socket;
        out("Member");
        member = new Member(this.in());
    }

    public void out(String out){
        try {
            socket.getOutputStream().write((out+"\n").getBytes("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String in(){
        String buffer = null;
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
            buffer = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public Member getMember() {
        return member;
    }

    public void run(){
        Room r = RoomManager.getRoomManager().getRoom(this);
        if (r==null)
            out(member.getUsername()+"进入"+member.getUsername()+"的房间");
        else
            out(member.getUsername()+"进入"+r.getName());
        RoomManager.getRoomManager().publish(this,member.getUsername()+"连接成功");
        String buffer = null;
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
            while ((buffer=br.readLine())!=null){
                if (buffer.equals("disconnect")){
                    RoomManager.getRoomManager().publish(this,member.getUsername() + "离开房间");
                    socket.close();
                    Room room = RoomManager.getRoomManager().findRoom(this);
                    room.removeMember(this);
                    if (room.getMembers().isEmpty()){
                        RoomManager.getRoomManager().getRooms().remove(room.getID());
                    }
                    break;
                }
                RoomManager.getRoomManager().publish(this,buffer);
            }
            br.close();
        } catch (Exception e) {
            clear();
        }
    }

    public void clear(){
        Room room = RoomManager.getRoomManager().findRoom(this);
        room.removeMember(this);
        if (room.getMembers().isEmpty()){
            RoomManager.getRoomManager().getRooms().remove(room.getID());
        }
    }
}
